<template>
  <div>
    <QuillEditor 
      ref="myQuillEditor" 
      theme="snow" 
      v-model:content="content" 
      :options="editorOptions"
      contentType="html" 
      @update:content="setValue"
    />
    <input 
      type="file" 
      hidden 
      accept=".jpg,.jpeg,.png,.gif" 
      ref="fileBtn" 
      @change="handleUpload" 
    />
  </div>
</template>

<script setup>
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ref, watch, onMounted, nextTick } from 'vue'

const props = defineProps({
  value: String
})

const emit = defineEmits(['updateValue'])

const content = ref('')
const myQuillEditor = ref(null)
const fileBtn = ref(null)

// 监听父组件传入的值
watch(() => props.value, (newVal) => {
  if (newVal && myQuillEditor.value && newVal !== content.value) {
    nextTick(() => {
      if (myQuillEditor.value.getHTML() !== newVal) {
        myQuillEditor.value.setHTML(newVal)
      }
    })
  }
})

const editorOptions = {
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{'header': [1, 2, 3, 4, 5, 6, false]}],
      [{'list': 'ordered'}, {'list': 'bullet'}],
      [{'indent': '-1'}, {'indent': '+1'}],
      [{'size': ['small', false, 'large', 'huge']}],
      [{'color': []}, {'background': []}],
      [{'font': []}],
      [{'align': []}],
      ['link', 'image']
    ]
  },
  placeholder: '请输入内容...'
}

const imgHandler = () => {
  fileBtn.value.click()
}

const setValue = () => {
  if (myQuillEditor.value) {
    const html = myQuillEditor.value.getHTML()
    if (html !== props.value) {
      emit('updateValue', html)
    }
  }
}

// 修改后的上传处理方法
const handleUpload = async (e) => {
  const files = e.target.files
  if (!files || files.length === 0) return
  
  const file = files[0]
  
  // 1. 检查文件类型和大小
  const validTypes = ['image/jpeg', 'image/png', 'image/gif']
  if (!validTypes.includes(file.type)) {
    alert('请上传 JPG/PNG/GIF 格式的图片')
    e.target.value = null
    return
  }
  
  const maxSize = 2 * 1024 * 1024 // 2MB
  if (file.size > maxSize) {
    alert('图片大小不能超过 2MB')
    e.target.value = null
    return
  }
  
  try {
    // 2. 将图片转换为 Base64
    const base64String = await fileToBase64(file)
    
    // 3. 获取当前编辑器实例和光标位置
    const quill = myQuillEditor.value.getQuill()
    const range = quill.getSelection(true)
    
    if (range) {
      // 4. 在光标位置插入 Base64 图片
      quill.insertEmbed(range.index, 'image', base64String)
      
      // 5. 移动光标到图片后面
      quill.setSelection(range.index + 1)
      
      // 6. 触发内容更新
      setValue()
    }
  } catch (error) {
    console.error('图片处理失败:', error)
    alert('图片处理失败，请重试')
  } finally {
    // 重置文件输入
    e.target.value = null
  }
}

// 将文件转换为 Base64 字符串
const fileToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    
    reader.onload = (event) => {
      resolve(event.target.result)
    }
    
    reader.onerror = (error) => {
      reject(error)
    }
    
    reader.readAsDataURL(file)
  })
}

onMounted(() => {
  nextTick(() => {
    if (myQuillEditor.value) {
      const quill = myQuillEditor.value.getQuill()
      
      if (quill.getModule('toolbar')) {
        quill.getModule('toolbar').addHandler('image', imgHandler)
      }
      
      if (props.value) {
        myQuillEditor.value.setHTML(props.value)
      }
    }
  })
})
</script>

<style scoped lang="scss">
:deep(.ql-editor) {
  min-height: 180px;
}

:deep(.ql-formats) {
  height: 21px;
  line-height: 21px;
}
</style>